package com.yoofn.framework.fragment

import android.databinding.DataBindingUtil
import android.databinding.ViewDataBinding
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.widget.SwipeRefreshLayout
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.yoofn.framework.R
import com.yoofn.framework.activity.BaseActivity
import com.yoofn.framework.config.ViewConfig
import com.yoofn.framework.function.PageFunction
import com.yoofn.framework.http.HttpNetData
import com.yoofn.framework.http.IHttpFramework


/**
 *
 * Created by kalshen on 17/6/2.
 * @描述 所有fragment 的基础类,可以设置懒加载
 */
abstract class BaseFragment<Binding : ViewDataBinding> : Fragment(), IHttpFramework {

    /**
     * fragment的配置参数
     */
    val viewConfig by lazy {
        setupConfig()
    }

    val pageFunction by lazy {
        PageFunction(activity as BaseActivity<*>)
    }
    /**
     * 下拉刷新控件
     */
    val swipeRefresh by lazy {
        SwipeRefreshLayout(activity).takeIf { viewConfig.shouldSwipeRefresh }
    }

    /**
     * 具有dataBinding 数据绑定特性的 contentView
     * 可以直接调用被layout 包裹的 控件资源id
     * 例:content.textView.text="hello"
     * 不懂的 自己去dataBinding
     */
    lateinit var contentView: Binding


    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?
                              , savedInstanceState: Bundle?): View? {

        contentView = DataBindingUtil.bind<Binding>(inflater?.inflate(viewConfig.layoutId, container, false))
        //初始化下拉刷新
        initSwipeRefresh()
        //处理页面交互
        doInteractive()
        //吐司 显示当前界面位置
        Toast.makeText(activity, this::class.java.simpleName, Toast.LENGTH_SHORT).show()
        return swipeRefresh ?: contentView.root
    }


    private fun initSwipeRefresh() {
        swipeRefresh?.addView(contentView.root)
        //swipeRefreshLayout的颜色默认设置成系统主题的颜色
        swipeRefresh?.setColorSchemeResources(R.color.colorAccent
                , R.color.colorPrimary
                , R.color.colorPrimaryDark)
        //设置刷新事件
        swipeRefresh?.setOnRefreshListener {
            viewConfig.httpNetData.let {
                if (it.isEmpty()) closeRefresh()
                else addRequest(*viewConfig.httpNetData)
            }
        }
    }

    private fun closeRefresh() {
        swipeRefresh?.postDelayed({ swipeRefresh?.isRefreshing = false }, 1000)
    }

    /**
     * 如果需要重写swipeRefreshLayout 的下拉刷新事件则调用该方法
     * 默认如果启用下拉刷新,请求队列是默认初始时候打请求队列
     */
    fun setSwipeRefresh(action: () -> Unit) {
        if (viewConfig.shouldSwipeRefresh) swipeRefresh?.setOnRefreshListener(action)
    }


    /**
     * 配置fragment 的基本特征
     * 例:是否开启下拉刷新,httpNetData...
     */
    abstract fun setupConfig(): ViewConfig

    /**
     * 配置ui与业务逻辑的交互
     */
    private fun doInteractive() {
        //初始化view
        initView()
        //初始化点击事件
        initClick()
    }

    /**
     * 初始化界面
     */
    abstract fun initView()

    /**
     * 初始化点击事件
     */
    abstract fun initClick()

    /**
     * 用于判别是否第一次resume 防止多次网络请求
     */
    var firstResume = true

    override fun onResume() {
        super.onResume()
        if (firstResume) {
            firstResume = false
        } else {
            if (viewConfig.shouldOnResumeRefresh) addRequest(*viewConfig.httpNetData)
        }
    }

    /**
     * 请求结束 统一的逻辑
     */
    override fun onRequestFinished(what: Int, unFinishedNetData: List<HttpNetData?>) {
        //是否开启下拉刷新并且请求队列是否都已经结束
        if (viewConfig.shouldSwipeRefresh && unFinishedNetData.isEmpty()) closeRefresh()
    }

    override fun onRequestStart(what: Int) {
        super.onRequestStart(what)
        if (viewConfig.shouldSwipeRefresh) swipeRefresh?.isRefreshing = true
    }

    /**
     * 改变 原本物理返回
     */
    fun setCustomBackPressedAction(backPressedAction: (() -> Boolean), isAlwaysIntercept: Boolean = false) {
        (activity as BaseActivity<*>).setCustomBackPressedAction(backPressedAction, isAlwaysIntercept)
    }

}